package 剑指Offer._1120;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/25 15:45
 * 表示数值的字符串
 * 数值中间可能有空格
 * 算法：字符串
 * 同主站的 65 题
 * 根据 e 或 E 将字符串分成两部分
 * 不管是正数或者小数都要有数字
 */
public class _20 {

    public boolean isNumber(String s) {
        String trim = s.trim();
        char[] array = trim.toCharArray();
        int index = -1, len = array.length;
        for (int i = 0; i < len; i++) {
            if (array[i] == 'e' || array[i] == 'E') {
                if (index == -1) index = i;
                else return false;
            }
        }
        boolean ans = true;
        if (index == -1) ans &= check(array, 0, len, false);
        else {
            ans &= check(array, 0, index, false);
            ans &= check(array, index + 1, len, true);
        }
        return ans;
    }
    public boolean check(char[] array, int start, int end, boolean mustInteger) {
        if (start >= end) return false;
        if (array[start] == '+' || array[start] == '-') ++start;
        boolean hasDot = false, hasNum = false;
        for (int i = start; i < end; i++) {
            char c = array[i];
            if (c == '.') {
                if (mustInteger || hasDot) return false;
                else hasDot = true;
            } else if (c >= '0' && c <= '9') hasNum = true;
            else return false;
        }
        return hasNum;
    }

}
